package com.hk.servlet;

import com.alibaba.fastjson.JSONObject;
import com.hk.model.News;
import com.hk.model.Product;
import com.hk.model.vo.ResultVO;
import com.hk.service.IProductService;
import com.hk.service.IProductMenuService;
import com.hk.service.impl.ProductServiceImpl;
import com.hk.service.impl.ProductMenuServiceImpl;
import com.hk.utils.CharacterEncoding;
import com.hk.utils.Tool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @Author: KangWang
 * Date: 2021/5/17 10:20
 * State：茶品展示 数据请求转发 控制层
 */
@WebServlet("/productDisplay")
public class ProductDisplayServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        统一字符编码
        CharacterEncoding.setCharacterEncodingResp(req, resp, "UTF-8");
        IProductService iProductService = new ProductServiceImpl();
        String page = Tool.nullToString(req.getParameter("page"));
        String limit = Tool.nullToString(req.getParameter("limit"));
        String tMenuId = Tool.nullToString(req.getParameter("tMenuId"));
        int i = Tool.parseInt(page);
        int size = Tool.parseInt(limit);
        int tMenuId1 = Tool.parseInt(tMenuId);
        //        根据sql语句规则将每页页码修改为需要数值
        int pageNum = Tool.pageNum(i,size);
        List<Product> productList = iProductService.findAll(pageNum, size, tMenuId1);
        int count = iProductService.count(-1, -1,tMenuId1);
        ResultVO<Product> resultVO = new ResultVO<Product>();
        PrintWriter out = resp.getWriter();
        if (!productList.isEmpty()) {
            resultVO.setStatus(1);
            resultVO.setMessage("success");
            resultVO.setPageNum(i);
//            总页数
            int pages = Tool.pageSize(size, count);
            resultVO.setPages(pages);
            resultVO.setTotal(count);
            resultVO.setList(productList);
        } else {
            resultVO.setStatus(0);
            resultVO.setMessage("error");
            resultVO.setPageNum(i);
            resultVO.setPages(0);
            resultVO.setTotal(count);
            resultVO.setList(productList);
        }
        String resultVOJSON = JSONObject.toJSONString(resultVO);
        out.write(resultVOJSON);
        out.flush();
        out.close();




    }

}
